package com.weiwei.WHadoop.io;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @author WangWeiwei
 * @version 1.0
 * @sine 17-3-8
 * 一对字符串的序列化操作实现
 */
public class TextPair implements WritableComparable<TextPair>{
    private Text first;
    private Text second;

    public TextPair(){
        set(new Text(),new Text());
    }

    public TextPair(String s1,String s2){
        set(new Text(s1),new Text(s2));
    }

    public Text getFirst() {
        return first;
    }

    public void setFirst(Text first) {
        this.first = first;
    }

    public Text getSecond() {
        return second;
    }

    public void setSecond(Text second) {
        this.second = second;
    }

    public TextPair(Text text, Text text2){
        set(text,text2);
    }

    private void set(Text text, Text text1) {
        this.first = text;
        this.second = text1;
    }


    public int compareTo(TextPair p) {
        int cmp = first.compareTo(p.first);
        if (cmp != 0){
            return cmp;
        }
        return second.compareTo(p.second);
    }

    /**
     * Serialize the fields of this object to <code>out</code>.
     *
     * @param out <code>DataOuput</code> to serialize this object into.
     * @throws IOException
     */
    @Override
    public void write(DataOutput out) throws IOException {
        first.write(out);
        second.write(out);
    }

    /**
     * Deserialize the fields of this object from <code>in</code>.
     * <p>
     * <p>For efficiency, implementations should attempt to re-use storage in the
     * existing object where possible.</p>
     *
     * @param in <code>DataInput</code> to deseriablize this object from.
     * @throws IOException
     */
    @Override
    public void readFields(DataInput in) throws IOException {
        first.readFields(in);
        second.readFields(in);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TextPair textPair = (TextPair) o;

        if (first != null ? !first.equals(textPair.first) : textPair.first != null) return false;
        return second != null ? second.equals(textPair.second) : textPair.second == null;
    }

    @Override
    public String toString() {
        return "TextPair{" +
                "first=" + first +
                ", second=" + second +
                '}';
    }

    @Override
    public int hashCode() {
        int result = first != null ? first.hashCode() : 0;
        result = 31 * result + (second != null ? second.hashCode() : 0);
        return result;
    }

}
